package it.softphone.cmc.maven;

import it.softphone.cmc.impl.ScriptletServiceClientImpl;
import it.softphone.cmc.shared.entity.Asset;
import it.softphone.cmc.shared.entity.ScriptletAsset;

import java.io.IOException;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

/**
 * 
 * Download scriptlet mojo
 *
 */
//@MojoRequiresProject(false)
//@MojoGoal("download")
@Mojo(	name="download",
		requiresProject=false,
		threadSafe=true)
public class ScriptletDownloadMojo extends AbstractScriptletQueryMojo {

	//@MojoParameter(expression="${outputDir}")
	@Parameter(property="outputDir")
	java.io.File outputDir;
	
	
	private  java.io.File checkFolder( java.io.File folder ) throws MojoExecutionException
	{
		if( folder !=null ) {
			
			if( !folder.exists() ) {
				if( !folder.mkdirs() ) {

					final String msg = String.format("error creating folder [%s] set as outputDir", folder );
					getLog().error(msg);
					throw new MojoExecutionException(msg);
					
				}
			}

			if( !folder.isDirectory() ) {
				
				final String msg = String.format("parameter [%s] is not a folder", folder);
				getLog().error(msg);
				throw new MojoExecutionException(msg);
			}
		}
		return folder;
	}
	
	/**
	 * 
	 * @param s
	 * @return
	 * @throws MojoExecutionException 
	 */
	private java.io.File getgAssetFolder( ScriptletAsset s ) throws MojoExecutionException {
		
		final boolean  groupid_empty = ( null==s.getGroupId() || s.getGroupId().isEmpty() );
		final boolean  version_empty = ( null==s.getVersion() || s.getVersion().isEmpty() );
		
		final java.io.File groupid_folder = new java.io.File(( groupid_empty ) ? NOGROUPID : s.getGroupId());
		
		java.io.File result = ( version_empty ) ? groupid_folder : new java.io.File( groupid_folder, s.getVersion() );
		
		return checkFolder((outputDir==null) ? result : new java.io.File( outputDir, groupid_folder.getPath() ));
	}
	
	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		
		final ScriptletServiceClientImpl service = super.createService();
		
		Asset filter = makeAssetFromParameter(service);
		
		System.out.println( "========================================");
		System.out.println( "> DOWNLOAD SCRIPTLET");		
		System.out.println();		
		System.out.printf( "> From [%s]\n", getBaseUrl() );		
		System.out.println( "========================================");

		java.util.List<String> keys = service.findScriptletKeys( filter );
		
		checkFolder(outputDir);
		
		for( String k :keys ) {
			
			System.out.printf( "Try to download scriptlet [%s] ..... ", k );
			
			ScriptletAsset s = service.findScriptletByKey(k);

			java.io.File folder = getgAssetFolder(s);

			System.out.println( " OK" );
		
			//
			// WRITE JSON
			//
			java.io.File fjson = new java.io.File( folder, String.format("%s.json", s.getArtifactId())) ;	

			final it.softphone.commons.json.server.JSONObject json = new it.softphone.commons.json.server.JSONObject(s);
			
			try {
				java.io.FileWriter fw = new java.io.FileWriter(fjson);
				
				json.put("content", "");
				
				final String payload = json.toString(4);
				
				fw.write( payload );
				
				fw.close();

				System.out.printf( "%s ..... saved!\n", fjson.getPath() );
				
				if( getLog().isDebugEnabled() ) {
					getLog().debug( payload );
				}
			} catch (Exception e) {
				getLog().warn(  String.format("error writing file [%s]", k), e);
				System.out.printf( "error saving json file %s\n", fjson.getPath() );
			}
					
					
			//
			// WRITE CONTENT
			//
			java.io.File f = new java.io.File( folder, String.format("%s.js", s.getArtifactId())) ;	
				
			try {
				java.io.FileWriter fw = new java.io.FileWriter(f);
				
				fw.write(s.getContent());
				
				fw.close();

				System.out.printf( " %s ..... saved!\n", f.getPath() );
				
			} catch (IOException e) {
				getLog().warn(  String.format("error writing file [%s]", k), e);

				System.out.printf( "error saving file %s\n", f.getPath() );
			}

		}

		System.out.println( "========================================");

	}

}
